package br.com.blutufi.gui;

import java.awt.AWTException;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import br.com.blutufi.AudioPlayer;
import br.com.blutufi.Server;
import br.com.blutufi.model.Contact;

public class SysTray implements ChangeListener {
	private static final String trayTitle = "Bluetooth Messager";
	private static final String labelExit = "Sair";
	private static final String errorAddingMessage = "Erro ao iniciar o System Tray.";
	private static final String imagePath = "res/message-black.png";
	private static final String altImagePath = "res/message-red.png";
	
	public static final Server btServer = new Server();
	
	public static Server getBtServer() {
		return btServer;
	}

	private TrayIcon trayIcon;
	private static Image icon;
	private static Image altIcon;
	//	private Image icon;
	//	private Image altIcon;
	private PopupMenu popup;
	private SystemTray systemTray;

	private MenuItem exitItem;

	private IconToggler iconToggler;

	static {
		SysTray.icon = SysTray.createImage(imagePath, trayTitle);
		SysTray.altIcon = SysTray.createImage(altImagePath, trayTitle);
	}

	public SysTray() {
		this.createAndShowTray();
	}

	private void createAndShowTray() {
		

		this.popup = new PopupMenu();
		this.trayIcon = new TrayIcon(SysTray.getIcon());
		this.trayIcon.setImageAutoSize(true);
		this.trayIcon.setToolTip(trayTitle);
		this.systemTray = SystemTray.getSystemTray();

		// Create a popup menu components
		this.exitItem = new MenuItem(labelExit);

		//Add components to popup menu
		this.popup.addSeparator();
		this.popup.add(this.exitItem);

		this.trayIcon.setPopupMenu(this.popup);

		try {
			this.systemTray.add(this.trayIcon);
		} catch (final AWTException e) {
			System.out.println(errorAddingMessage);
			e.printStackTrace();
			return;
		}

		this.trayIcon.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				ContactsChatFrame.getInstance().setVisible(true);
				resetIcon();
			}
		});

		this.exitItem.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO: Parar servidor bluetooth
				SysTray.this.systemTray.remove(SysTray.this.trayIcon);
				System.exit(0);
			}
		});
	}

	public static Image getIcon() {
		return SysTray.icon;
	}

	public static Image getAltIcon() {
		return SysTray.altIcon;
	}

	private void resetIcon() {
		if (this.iconToggler != null) {
			this.iconToggler.stop();
			this.iconToggler = null;
		}

		if (this.trayIcon.getImage() == SysTray.getAltIcon()) {
			this.trayIcon.setImage(SysTray.getIcon());
		}
	}

	//Obtain the image URL
	private static Image createImage(String path, String description) {
		final URL imageURL = SysTray.class.getResource(path);

		if (imageURL == null) {
			System.err.println("Resource not found: " + path);
			return null;
		} else {
			final ImageIcon imageIcon = new ImageIcon(imageURL, description);
			final Image image = imageIcon.getImage();
			return image;
		}
	}

	public static Image resizeImage(Image image, int width, int height) {
		final BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null),
				BufferedImage.TYPE_INT_ARGB);
		final Graphics g = bi.createGraphics();
		g.drawImage(image, 0, 0, width, height, null);
		final ImageIcon newIcon = new ImageIcon(bi);
		return newIcon.getImage();
	}

	@Override
	public void stateChanged(ChangeEvent e) {
		Object obj = e.getSource();
		if (obj instanceof Contact) {
			Contact contact = (Contact) obj;

			this.trayIcon.setImage(SysTray.getAltIcon());

			if (iconToggler == null) {
				this.iconToggler = new IconToggler();
			}

			String[] history = contact.getHistory().split("\n");
			String lastMessage = history[history.length - 1];
			// PopupEnabled
			this.trayIcon.displayMessage("Watchdog", contact.getName() + ": " + lastMessage,
					TrayIcon.MessageType.WARNING);

			//SoundEnabled
			try {
				String audioFile = this.getClass().getResource("res/sounds/alert.wav").getFile();
				AudioPlayer.playAudio(audioFile);
			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	private void toggleIcon() {
		if (this.trayIcon.getImage() != SysTray.getAltIcon()) {
			this.trayIcon.setImage(SysTray.getAltIcon());
		} else {
			this.trayIcon.setImage(SysTray.getIcon());
		}

	}

	private class IconToggler implements Runnable {
		private boolean run = true;

		private Thread thread;

		public IconToggler() {
			super();
			this.thread = new Thread(this);
			this.thread.start();
		}

		@Override
		public void run() {
			while (run) {
				SysTray.this.toggleIcon();
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
				}
			}
		}

		public void stop() {
			this.run = false;
		}
	}
}